package com.youlu.campus.admin.banner.service.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.admin.banner.dto.BannerConfigUpdateRequest;
import com.youlu.campus.admin.banner.entity.BannerConfig;
import com.youlu.campus.admin.banner.service.BannerConfigService;
import com.youlu.campus.admin.base.BaseService;
import com.youlu.campus.admin.utils.JsonUtil;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.service.activity.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

@Slf4j
@Service
public class BannerConfigServiceImpl extends BaseService implements BannerConfigService {
    @Autowired
    private ActivityService activityService;

    @Override
    public boolean create(BannerConfig bannerConfig) {
        log.info(":>>> 开始创建Banner配置:{}", JSON.toJSONString(bannerConfig));
        if (Objects.isNull(bannerConfig) || StringUtils.isBlank(bannerConfig.getImageUrl()) || Objects.isNull(bannerConfig.getLocation())) {
            log.error(":>>> 创建Banner参数错误");
            throw new BusinessException("参数错误");
        }
        BannerConfig insert = new BannerConfig();
        BeanUtils.copyProperties(bannerConfig, insert);
        insert.setCreatedTime(new Date());
        insert.setStatus(Boolean.TRUE);
        if(StringUtils.isNotBlank(bannerConfig.getActivityId())){
            ActivityInfo activityInfo = activityService.findOne(bannerConfig.getActivityId());
            if (!Objects.isNull(activityInfo)) {
                insert.setActivityName(activityInfo.getName());
            }
        }
        insert = mongoTemplate.insert(insert);
        log.info(":>>> 创建的Banner配置为:{}", JSON.toJSONString(insert));
        return true;
    }

    @Override
    public boolean update(BannerConfig bannerConfig) {
        log.info(":>>> 开始修改Banner配置:{}", JSON.toJSONString(bannerConfig));
        if (Objects.isNull(bannerConfig) || StringUtils.isBlank(bannerConfig.getId()) ||
                (Objects.isNull(bannerConfig.getLocation()) &&
                        Objects.isNull(bannerConfig.getStatus()))) {
            log.error(":>>> 修改Banner参数错误");
            throw new BusinessException("参数错误");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(bannerConfig.getId()));
        boolean exist = mongoTemplate.exists(query, BannerConfig.class);
        if (!exist) {
            log.error(":>>> 修改Banner参数错误,id:{} 数据不存在");
            throw new BusinessException("数据不存在");
        }
        Update update = new Update();
        if (StringUtils.isNotBlank(bannerConfig.getTitle())) {
            update.set("title", bannerConfig.getTitle());
        }
        if (StringUtils.isNotBlank(bannerConfig.getImageUrl())) {
            update.set("imageUrl", bannerConfig.getImageUrl());
        }
        if (StringUtils.isNotBlank(bannerConfig.getLocation())) {
            update.set("location", bannerConfig.getLocation());
        }
        if (StringUtils.isNotBlank(bannerConfig.getInnerLinks())) {
            bannerConfig.setOuterLinks("");
            update.set("innerLinks", bannerConfig.getInnerLinks());
            update.set("outerLinks", null);
        }
        if (StringUtils.isNotBlank(bannerConfig.getOuterLinks())) {
            bannerConfig.setInnerLinks("");
            update.set("outerLinks", bannerConfig.getOuterLinks());
            update.set("innerLinks", null);
        }
        if (!Objects.isNull(bannerConfig.getPriority())) {
            update.set("priority", bannerConfig.getPriority());
        }
        if (!Objects.isNull(bannerConfig.getStatus())) {
            update.set("status", bannerConfig.getStatus());
        }
        if (StringUtils.isNotBlank(bannerConfig.getLinkerType())) {
            update.set("linkerType", bannerConfig.getLinkerType());
        }
        if (StringUtils.isNotBlank(bannerConfig.getAppId())) {
            update.set("appId", bannerConfig.getAppId());
        }
        if (StringUtils.isNotBlank(bannerConfig.getPlatform())) {
            update.set("platform", bannerConfig.getPlatform());
        }
        if (StringUtils.isNotBlank(bannerConfig.getActivityId())) {
            update.set("activityId", bannerConfig.getActivityId());
        }
        update.set("updatedTime", bannerConfig.getUpdatedTime());
        UpdateResult result = mongoTemplate.updateFirst(query, update, BannerConfig.class);
        if (result.getModifiedCount() > 0) {
            log.info("修改Banner成功");
        }
        return true;
    }

    @Override
    public boolean delete(String id) {
        log.info(":>>> 开始删除Banner配置:{}", id);
        if (StringUtils.isBlank(id)) {
            log.error(":>>> 删除Banner参数错误");
            throw new BusinessException("参数错误");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        DeleteResult result = mongoTemplate.remove(query, BannerConfig.class);
        return result.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public Page<BannerConfig> list(BannerConfig bannerConfig, Integer page, Integer pageSize) {
        log.info("查询话题信息列表，参数:{},page:{},pageSize:{}", JsonUtil.toJSON(bannerConfig), page, pageSize);
        Query query = new Query();
        if (StringUtils.isNotBlank(bannerConfig.getTitle())) {
            Pattern pattern = Pattern.compile("^.*" + bannerConfig.getTitle() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("title").regex(pattern));
        }
        if (Objects.nonNull(bannerConfig.getStatus())) {
            query.addCriteria(Criteria.where("status").is(bannerConfig.getStatus()));
        }
        if (StringUtils.isNotBlank(bannerConfig.getLocation())) {
            query.addCriteria(Criteria.where("location").is(bannerConfig.getLocation()));
        }
        if (StringUtils.isNotBlank(bannerConfig.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(bannerConfig.getActivityId()));
        }
        if (StringUtils.isNotBlank(bannerConfig.getPlatform())) {
            query.addCriteria(Criteria.where("platform").is(bannerConfig.getPlatform()));
        }
        if (StringUtils.isNotBlank(bannerConfig.getAppId())) {
            query.addCriteria(Criteria.where("appId").is(bannerConfig.getAppId()));
        }
        query.addCriteria(Criteria.where("deleted").is(false));
        long count = mongoTemplate.count(query, BannerConfig.class);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<BannerConfig> topicInfos = mongoTemplate.find(query.with(pageRequest), BannerConfig.class);
        return PageableExecutionUtils.getPage(topicInfos, pageRequest, () -> count);
    }

    @Override
    public boolean updateStatus(BannerConfigUpdateRequest updateRequest) {

        log.info(":>>> 开始修改Banner状态:{}", JSON.toJSONString(updateRequest));
        if (StringUtils.isBlank(updateRequest.getId()) &&
                Objects.isNull(updateRequest.getStatus())) {
            log.error(":>>> 修改Banner状态错误");
            throw new BusinessException("参数错误");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(updateRequest.getId()));
        Update update = new Update();
        update.set("status", updateRequest.getStatus());
        update.set("updatedTime", new Date());
        UpdateResult result = mongoTemplate.updateFirst(query, update, BannerConfig.class);
        return result.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public BannerConfig findOne(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, BannerConfig.class);
    }

    @Override
    public List<BannerConfig> findBy(String location) {
        Query query = new Query().addCriteria(Criteria.where("location").is(location));
        return mongoTemplate.find(query, BannerConfig.class);
    }

    @Override
    public List<BannerConfig> findByLocations(List<String> locationList) {
        Query query = new Query().addCriteria(Criteria.where("location").in(locationList));
        return mongoTemplate.find(query, BannerConfig.class);
    }
}
